import { NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { verifyToken } from '@/app/lib/auth';
import prisma from '@/app/lib/prisma';
import { callErnieBot } from '@/app/lib/ernie';

export async function GET() {
  try {
    const cookieStore = await cookies();
    const token = cookieStore.get('auth-token')?.value;

    if (!token) {
      return NextResponse.json(
        { message: '请先登录后再使用此功能' },
        { status: 401 }
      );
    }

    const payload = verifyToken(token);
    if (!payload) {
      return NextResponse.json(
        { message: '登录已过期，请重新登录' },
        { status: 401 }
      );
    }

    // 获取用户信息和饮食记录
    const [user, records] = await Promise.all([
      prisma.user.findUnique({
        where: { id: payload.userId },
      }),
      prisma.dietRecord.findMany({
        where: { userId: payload.userId },
        orderBy: { date: 'desc' },
        take: 30, // 获取最近30天的记录
      }),
    ]);

    if (!user) {
      throw new Error('用户不存在');
    }

    // 计算平均营养摄入
    const totalRecords = records.length;
    const averages = {
      calories: records.reduce((sum, r) => sum + r.calories, 0) / totalRecords || 0,
      protein: records.reduce((sum, r) => sum + r.protein, 0) / totalRecords || 0,
      carbs: records.reduce((sum, r) => sum + r.carbs, 0) / totalRecords || 0,
      fat: records.reduce((sum, r) => sum + r.fat, 0) / totalRecords || 0,
    };

    // 生成提示词
    const prompt = `
      作为营养师，请根据以下信息提供健康建议，返回JSON格式：

      用户信息：
      - 性别：${user.gender || '未知'}
      - 年龄：${user.age || '未知'}
      - 身高：${user.height || '未知'}cm
      - 体重：${user.weight || '未知'}kg
      - 健康目标：${user.healthGoal || '未知'}

      平均每日营养摄入：
      - 热量：${averages.calories.toFixed(0)}卡路里
      - 蛋白质：${averages.protein.toFixed(1)}g
      - 碳水化合物：${averages.carbs.toFixed(1)}g
      - 脂肪：${averages.fat.toFixed(1)}g

      请返回如下JSON格式：
      {
        "generalAdvice": "总体建议",
        "nutritionAdvice": ["营养建议1", "营养建议2"],
        "habitAdvice": ["生活习惯建议1", "生活习惯建议2"],
        "exerciseAdvice": ["运动建议1", "运动建议2"]
      }
    `;

    const aiResponse = await callErnieBot(prompt);
    let advice;

    try {
      const cleanedResponse = aiResponse
        .replace(/^```json\s*/, '')
        .replace(/```$/, '')
        .trim();
      advice = JSON.parse(cleanedResponse);
    } catch (error) {
      console.error('解析AI响应失败:', error);
      // 提供默认建议
      advice = {
        generalAdvice: "根据您的饮食记录，建议您保持均衡的饮食习惯，确保营养摄入充足。",
        nutritionAdvice: [
          "注意每日蛋白质的摄入",
          "增加蔬菜水果的摄入量",
          "控制油盐摄入",
        ],
        habitAdvice: [
          "保持规律的三餐",
          "避免夜间进食",
          "细嚼慢咽，享受进食过程",
        ],
        exerciseAdvice: [
          "每周进行3-5次有氧运动",
          "适当进行力量训练",
          "保持运动和饮食的平衡",
        ],
      };
    }

    return NextResponse.json({ advice });
  } catch (error) {
    console.error('获取健康建议错误:', error);
    return NextResponse.json(
      { message: '获取健康建议失败' },
      { status: 500 }
    );
  }
} 